<!-- 路由 -->
<template>
    <el-row>
        <el-col class="page-top-btn-group">
            <el-button size="small" type="primary" icon="Plus" @click="showAddForm(0)">
                新增
            </el-button>
            <el-button size="small" type="primary" icon="Delete" @click="delAllChose()">
                删除选中
            </el-button>

            <el-button size="small" type="warning" icon="Refresh" @click="refreshAll()">
                刷新缓存
            </el-button>
        </el-col>
    </el-row>

    <el-row>
        <el-col>
            <el-tree ref="categoryTree" :data="routes" node-key="id" show-checkbox :expand-on-click-node="false">
                <template #default="{ data }">
                    <span>{{ data.name }}</span>

                    <el-icon size="small" class="m-l-5 m-r-5" @click="showAddForm(data.id)">
                        <Plus />
                    </el-icon>
                    <el-icon size="small" class="m-l-5 m-r-5" @click="showEditForm(data)">
                        <Edit />
                    </el-icon>

                </template>
            </el-tree>
        </el-col>
    </el-row>

    <!-- 新增弹框 -->
    <el-dialog v-model="addForm.showDialog" title="新增分类">
        <el-form ref="addFormRef" :model="addForm.formData" label-width="auto" :rules="addForm.rules">

            <el-form-item label="名称" prop="name">
                <el-input v-model="addForm.formData.name"></el-input>
            </el-form-item>

            <el-form-item label="上级分类" prop="pid">

                <el-tree-select v-model="addForm.formData.pid" :data="categorySelect"
                    :props="{ checkStrictly: true, label: 'name', value: 'id' }" check-strictly value-key="id"
                    :render-after-expand="false">

                    <template #default="{ data }">
                        <span>{{ data.name }}</span>
                    </template>
                </el-tree-select>

            </el-form-item>

            <el-form-item label="图片" prop="cover">
                <el-input type="hidden" name="cover" v-model="addForm.formData.cover"></el-input>
                <Upload :key="addForm.uuid" @on-success="addFormImgUploadSuccess"></Upload>
            </el-form-item>

            <el-form-item label="唯一标识" prop="code">
                <el-input v-model="addForm.formData.code" placeholder="顶级分类时必填"></el-input>
            </el-form-item>

            <el-form-item label="排序值" prop="sort">
                <el-input v-model="addForm.formData.sort"></el-input>
            </el-form-item>

            <el-button @click="addSub(addFormRef)" :loading="addForm.onSubmiting">提交</el-button>
        </el-form>
    </el-dialog>

    <!-- 编辑弹框 -->
    <el-dialog v-model="editForm.showDialog" title="编辑分类">
        <el-form ref="editFormRef" :model="editForm.formData" label-width="auto" :rules="editForm.rules">

            <el-form-item label="名称" prop="name">
                <el-input v-model="editForm.formData.name"></el-input>
            </el-form-item>

            <el-form-item label="上级分类" prop="pid">

                <el-tree-select v-model="editForm.formData.pid" :data="categorySelect"
                    :props="{ checkStrictly: true, label: 'name', value: 'id' }" check-strictly value-key="id"
                    :render-after-expand="false">

                    <template #default="{ data }">
                        <span>{{ data.name }}</span>
                    </template>
                </el-tree-select>

            </el-form-item>

            <el-form-item label="图片" prop="cover">
                <el-input type="hidden" name="cover" v-model="editForm.formData.cover"></el-input>
                <Upload :key="editForm.uuid" @on-success="editFormImgUploadSuccess" v-model:file-list="editCover">
                </Upload>
            </el-form-item>

            <el-form-item label="唯一标识" prop="code">
                <el-input v-model="editForm.formData.code" placeholder="顶级分类时必填"></el-input>
            </el-form-item>

            <el-form-item label="排序值" prop="sort">
                <el-input v-model="editForm.formData.sort"></el-input>
            </el-form-item>

            <el-button @click="editSub(editFormRef)" :loading="editForm.onSubmiting">更新</el-button>
        </el-form>
    </el-dialog>
    <!-- END 编辑弹框 -->
</template>

<script setup>
import Upload from '@/components/Upload.vue';

import { ref, onMounted, reactive } from 'vue'
import categoryApi from '@/api/category'
import RouteCode from '@/constants/RouteCode'
import msgUtil from '@/utils/msgUtil'

import arr from '@/utils/arr'
import str from '@/utils/str'

// tree 组件对象
const categoryTree = ref()
const addFormRef = ref()
const editFormRef = ref()

const routes = ref([])
// 上级下拉框
const categorySelect = ref([]);

// 新增表单的初始数据
const initAddForm = () => {
    return {
        pid: 0,
        sort: 0,
        code: '',
        name: '',
        cover: '',
    }
};
const addForm = ref({
    showDialog: false,
    onSubmiting: false,
    formData: initAddForm(),
    uuid: '',
    rules: {
        name: [{ required: true, message: '必填' }],
        code: [{
            message: '必填', validator(rule, value, cb) {
                if (addForm.value.formData.pid == 0 && value === '') {
                    cb(new Error('顶级分类时唯一标识必填'))
                } else {
                    cb()
                }
            }
        }],

        pid: [{ required: true, message: '必填' }],
    }
})
const editForm = ref({
    showDialog: false,
    onSubmiting: false,
    uuid: '',
    formData: {},
    rules: {
        name: [{ required: true, message: '必填' }],
        pid: [{ required: true, message: '必填' }],
        code: [{
            message: '必填', validator(rule, value, cb) {
                if (editForm.value.formData.pid == 0 && value === '') {
                    cb(new Error('顶级分类时唯一标识必填'))
                } else {
                    cb()
                }
            }
        }],

    }
})

// 加载数据
function loadAllCategory() {
    categoryApi.all().then(res => {
        msgUtil.alertIfError(res).then(apiRes => {
            routes.value = apiRes.data.tree;
            categorySelect.value = [
                {
                    name: '顶级分类',
                    id: 0,
                    children: apiRes.data.tree,
                }
            ]
        })
    })
}


// 弹窗新增
function showAddForm(pid = 0) {
    addForm.value.showDialog = true
    addForm.value.uuid = str.now()
    addForm.value.formData = arr.merge(initAddForm(), { pid })
}

// 新增图片上传成功
function addFormImgUploadSuccess(res) {
    addForm.value.formData.cover = res.url
}

// 提交新增
function addSub(formEl) {

    formEl.validate((valid, fields) => {
        if (!valid) {
            return;
        }
        if (addForm.value.onSubmiting) {
            return;
        }
        addForm.value.onSubmiting = true;

        categoryApi.add(addForm.value.formData).then(res => {
            msgUtil.handleApiRes(res, {
                onApiSuccess() {
                    loadAllCategory();
                    addForm.value.showDialog = false
                }
            })
        }).finally(() => {
            addForm.value.onSubmiting = false;
        })
    })

}


const editCover = ref([]);

function editFormImgUploadSuccess(res) {
    editForm.value.formData.cover = res.url
}

// 弹窗编辑
function showEditForm(data) {
    editForm.value.showDialog = true
    if (data.cover) {
        editCover.value = [
            {
                name: data.cover,
                url: data.cover,
            }
        ]
    } else {
        editCover.value = [
        ]
    }

    editForm.value.uuid = str.now()
    editForm.value.formData = arr.coverFieldType(data, { type: 'string' })
}


// 提交编辑
function editSub(formEl) {

    formEl.validate((valid, fields) => {
        if (!valid) {
            return;
        }
        if (editForm.value.onSubmiting) {
            return;
        }
        editForm.value.onSubmiting = true;

        categoryApi.update(editForm.value.formData).then(res => {
            msgUtil.handleApiRes(res, {
                onApiSuccess() {
                    loadAllCategory();
                    editForm.value.showDialog = false
                }
            })
        }).finally(() => {
            editForm.value.onSubmiting = false;
        })
    })
}

// 删除所有选中
function delAllChose() {

    let keys = categoryTree.value.getCheckedKeys();
    if (keys.length === 0) {
        msgUtil.warnMsg({
            message: '请先选择'
        })
        return;
    }
    msgUtil.dangerAction({
        message: '删除操作不可逆，请谨慎操作'
    })
        .then(res => {
            categoryApi.del(keys).then(res => {
                msgUtil.handleApiRes(res, {
                    onApiSuccess() {
                        loadAllCategory();

                    }
                })
            })
        })

}

function refreshAll() {
    categoryApi.refreshAll().then(res => {
        msgUtil.handleApiRes(res)
    })
}

onMounted(() => {
    loadAllCategory();
})

</script>
<style>
.route-type {
    font-size: small;
    margin-left: 20px;
}

.route-type-1 {
    color: #409EFF;
}

.route-type-2 {
    color: #33699f;
}

.route-type-3 {
    color: #67C23A;
}

.route-type-4 {
    color: #F56C6C;
}
</style>